package belf.migrate.engine.verify;

import belf.migrate.api.exception.CatalogException;
import belf.migrate.api.model.VerifyModel;
import belf.migrate.api.table.schema.AbstractJdbcCatalog;
import belf.migrate.api.taskconf.SinkConf;
import belf.migrate.api.taskconf.SourceConf;
import belf.migrate.engine.job.CatalogCreator;
import belf.migrate.engine.job.Result;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class VerifyProcedure {


    private static Gson gson = new Gson();
    public static JsonObject verify(VerifyModel verifyModel) {

        SourceConf sourceConf = verifyModel.getSourceConf();
        SinkConf sinkConf = verifyModel.getSinkConf();
        try {
            AbstractJdbcCatalog sourceCatalog = CatalogCreator.createCatalog(
                    sourceConf.getCatalogName(),
                    sourceConf.getDatabaseName(),
                    sourceConf.getSchemaName(), sourceConf.getConnectionConf(), sourceConf.isCaseSensitive());
            AbstractJdbcCatalog sinkCatalog = CatalogCreator.createCatalog(
                    sinkConf.getCatalogName(),
                    sinkConf.getDatabaseName(),
                    sinkConf.getSchemaName(), sinkConf.getConnectionConf(), sinkConf.isCaseSensitive());
            if (!sinkCatalog.procedureExists(sinkConf.getDatabaseName(), sinkConf.getSchemaName(), verifyModel.getName())) {
                return gson.toJsonTree(Result.fail("存储过程未创建成功，存储过程不存在！")).getAsJsonObject();
            }

        } catch (CatalogException e) {
            log.error("校验存储过程失败", e);
            return gson.toJsonTree(Result.fail(e.getMessage())).getAsJsonObject();
        }
        return gson.toJsonTree(Result.success()).getAsJsonObject();

    }
}
